package br.ufms.facom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class TrucoBTActivity extends Activity {


	Truco truco;

	ImageView vira;

	ImageView carta1;
	ImageView carta2;
	ImageView carta3;

	ImageView cartaadv;
	ImageView cartamao;

	TextView placaradv;
	TextView placarmao;

	int pontuacaoadv;
	int pontuacaomao;

	int ultimajogada;
	int ultimajogadaadv;
	int parcialpontuacaoadv;
	int parcialpontuacaomao;
	int qntturno;
	int valortruco;

	public boolean isRunning = false;

	Button botaotruco;

	SharedPreferences previewSizePref;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mesa_card_activity);

		previewSizePref = getSharedPreferences("PREF",MODE_PRIVATE);
		CarregaLayout();
		startReceiverThread();
		truco = new Truco();
		truco.embaralha();
		botaotruco = (Button) findViewById(R.id.botaotruco);
		vira = (ImageView) findViewById(R.id.vira);
		carta1 = (ImageView) findViewById(R.id.carta1);
		carta2 = (ImageView) findViewById(R.id.carta2);
		carta3 = (ImageView) findViewById(R.id.carta3);

		cartaadv = (ImageView) findViewById(R.id.cartaadv);
		cartamao = (ImageView) findViewById(R.id.cartamao);

		pontuacaoadv = 0;
		pontuacaomao = 0;
		parcialpontuacaomao = 0;
		parcialpontuacaoadv = 0;
		qntturno = 0;
		valortruco = 0;
		placaradv = (TextView) findViewById(R.id.placaradv);
		placarmao = (TextView) findViewById(R.id.placarmao);

		placaradv.setText( String.valueOf(pontuacaoadv));
		placarmao.setText( String.valueOf(pontuacaomao));

		cartaadv.setVisibility(View.GONE);
		cartamao.setVisibility(View.GONE);

		carta1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ( previewSizePref.getInt("server", 0) == truco.turno ){

					carta1.setVisibility(View.GONE);
					if ( cartamao.getVisibility()==View.GONE )
						cartamao.setVisibility(View.VISIBLE);
					cartamao.setImageResource(Resource.getResource(truco.baralho.get(1)));
					truco.setTurno(truco.getTurno() == 0 ? 1 : 0);
					ultimajogada =1;
					if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
						if (  truco.cards.indexOf(truco.baralho.get(ultimajogadaadv)) > truco.procura(truco.baralho.get(1)) ) {
							parcialpontuacaoadv++;
						}
						else{
							parcialpontuacaomao++;
						}
						cartaadv.setVisibility(View.GONE);
						cartamao.setVisibility(View.GONE);
						qntturno++;
						if ( qntturno == 3){
							valortruco=valortruco>0?valortruco-1:valortruco;
							if ( parcialpontuacaoadv > parcialpontuacaomao) 
								pontuacaoadv= pontuacaoadv + valortruco + 1;
							else
								pontuacaomao= pontuacaomao + valortruco + 1;
							placaradv.setText( String.valueOf(pontuacaoadv));
							placarmao.setText( String.valueOf(pontuacaomao));
							reiniciaPartida();
						}
					}
					sendMessage("1 ");
				}
			}
		});

		carta2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ( previewSizePref.getInt("server", 0) == truco.turno ){
					carta2.setVisibility(View.GONE);
					if ( cartamao.getVisibility()==View.GONE )
						cartamao.setVisibility(View.VISIBLE);
					cartamao.setImageResource(Resource.getResource(truco.baralho.get(2)));
					truco.setTurno(truco.getTurno() == 0 ? 1 : 0);
					ultimajogada =2;

					if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
						if (  truco.cards.indexOf(truco.baralho.get(ultimajogadaadv)) > truco.procura(truco.baralho.get(2)) ) {
							parcialpontuacaoadv++;
						}
						else{
							parcialpontuacaomao++;
						}
						cartaadv.setVisibility(View.GONE);
						cartamao.setVisibility(View.GONE);
						qntturno++;
						if ( qntturno == 3){
							valortruco=valortruco>0?valortruco-1:valortruco;
							if ( parcialpontuacaoadv > parcialpontuacaomao) 
								pontuacaoadv= pontuacaoadv + valortruco + 1;
							else
								pontuacaomao= pontuacaomao + valortruco + 1;
							placaradv.setText( String.valueOf(pontuacaoadv));
							placarmao.setText( String.valueOf(pontuacaomao));
							reiniciaPartida();
						}
					}
					sendMessage("2 ");
				}
			}
		});

		carta3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ( previewSizePref.getInt("server", 0) == truco.turno ){
					carta3.setVisibility(View.GONE);
					if ( cartamao.getVisibility()==View.GONE )
						cartamao.setVisibility(View.VISIBLE);
					cartamao.setImageResource(Resource.getResource(truco.baralho.get(3)));
					truco.setTurno(truco.getTurno() == 0 ? 1 : 0);
					ultimajogada =3;

					if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
						if (  truco.cards.indexOf(truco.baralho.get(ultimajogadaadv)) > truco.procura(truco.baralho.get(3)) ) {
							parcialpontuacaoadv++;
						}
						else{
							parcialpontuacaomao++;
						} 
						cartaadv.setVisibility(View.GONE);
						cartamao.setVisibility(View.GONE);
						qntturno++;
						if ( qntturno == 3){
							valortruco=valortruco>0?valortruco-1:valortruco;
							if ( parcialpontuacaoadv > parcialpontuacaomao) 
								pontuacaoadv= pontuacaoadv + valortruco + 1;
							else
								pontuacaomao= pontuacaomao + valortruco + 1;
							placaradv.setText( String.valueOf(pontuacaoadv));
							placarmao.setText( String.valueOf(pontuacaomao));
							reiniciaPartida();
						}
					}
					sendMessage("3 ");
				}
			}
		});

		vira.setImageResource(Resource.getResource(truco.baralho.get(0)));
		carta1.setImageResource(Resource.getResource(truco.baralho.get(1)));
		carta2.setImageResource(Resource.getResource(truco.baralho.get(2)));
		carta3.setImageResource(Resource.getResource(truco.baralho.get(3)));
		enviaBaralho();
	}

	public void pedeTruco(View view){
		if ( previewSizePref.getInt("server", 0) == truco.turno ){
			if ( valortruco == 9)
				botaotruco.setVisibility(View.GONE);
			sendMessage("4 ");
		}
	}


	public void reiniciaPartida(){
		verificaFim();
		truco.embaralha();
		parcialpontuacaomao = 0;
		parcialpontuacaoadv = 0;
		valortruco = 0;
		cartaadv.setVisibility(View.GONE);
		cartamao.setVisibility(View.GONE);
		botaotruco.setVisibility(View.VISIBLE);
		carta1.setVisibility(View.VISIBLE);
		carta2.setVisibility(View.VISIBLE);
		carta3.setVisibility(View.VISIBLE);
		vira.setImageResource(Resource.getResource(truco.baralho.get(0)));
		carta1.setImageResource(Resource.getResource(truco.baralho.get(1)));
		carta2.setImageResource(Resource.getResource(truco.baralho.get(2)));
		carta3.setImageResource(Resource.getResource(truco.baralho.get(3)));
		botaotruco.setText("Truco!");
		qntturno = 0;
		if ( previewSizePref.getInt("server", 1) == 1) {
			String msg;
			truco.turno=1;
			msg = "100 "+truco.getCartas();
			sendMessage(msg);
		}
	}

	public void enviaBaralho(){
		if ( previewSizePref.getInt("server", 1) == 1) {
			String msg;
			truco.turno=1;
			msg = "100 "+truco.getCartas();
			sendMessage(msg);
		}
	}

	public void CarregaLayout() {
		Log.i("Pai", "load");
	}
	public void sendMessage(String str) {
		Log.i("Pai", "send");
	}
	public String receiveMessage() {
		Log.i("Pai", "receive");
		return null;
	}

	private void startReceiverThread() {
		isRunning = true;
		(new Thread() {

			public void run() {

				while (true) {
					if(isRunning){
						String[] msgArray = new String[10];
						msgArray = receiveMessage().split(" ",100);

						Log.e("incoming: " , msgArray[0].toString());

						Message msg = new Message();
						msg.what = Integer.parseInt(msgArray[0]);
						msgArray.toString();
						if ( msgArray[0].contains("100") ){
							handleReceivedMessage(msgArray);
							handler.sendMessage(msg);
						}
						else
							handler.sendMessage(msg);
					}
					else break;
				}

			}

			private Handler handler = new Handler()
			{
				public void handleMessage(android.os.Message msg) {
					truco.setTurno(previewSizePref.getInt("server", 0) == truco.turno?truco.turno:truco.getTurno() == 0 ? 1 : 0);				
					if ( msg.what == 1 )  //Recebeu a carta 1
					{
						if ( cartaadv.getVisibility()==View.GONE )
							cartaadv.setVisibility(View.VISIBLE);
						cartaadv.setImageResource(Resource.getResource(truco.baralho.get(4))); 
						ultimajogadaadv=4;
						if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
							if (  truco.cards.indexOf(truco.baralho.get(4)) > truco.cards.indexOf(truco.baralho.get(ultimajogada)) ) {
								parcialpontuacaoadv++;
							}
							else{
								parcialpontuacaomao++;
							}
							cartaadv.setVisibility(View.GONE);
							cartamao.setVisibility(View.GONE);
							qntturno++;
							if ( qntturno == 3){
								valortruco=valortruco>0?valortruco-1:valortruco;
								if ( parcialpontuacaoadv > parcialpontuacaomao) 
									pontuacaoadv= pontuacaoadv + valortruco + 1;
								else
									pontuacaomao= pontuacaomao + valortruco + 1;
								placaradv.setText( String.valueOf(pontuacaoadv));
								placarmao.setText( String.valueOf(pontuacaomao));
								reiniciaPartida();
							}
						}
					}
					else if ( msg.what == 2 ) //Recebeu a carta 2
					{
						if ( cartaadv.getVisibility()==View.GONE )
							cartaadv.setVisibility(View.VISIBLE);
						cartaadv.setImageResource(Resource.getResource(truco.baralho.get(5)));    
						ultimajogadaadv=5;
						if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
							if (  truco.cards.indexOf(truco.baralho.get(5)) > truco.cards.indexOf(truco.baralho.get(ultimajogada)) ) {
								parcialpontuacaoadv++;
							}
							else{
								parcialpontuacaomao++;
							} 
							cartaadv.setVisibility(View.GONE);
							cartamao.setVisibility(View.GONE);
							qntturno++;
							if ( qntturno == 3){
								valortruco=valortruco>0?valortruco-1:valortruco;
								if ( parcialpontuacaoadv > parcialpontuacaomao) 
									pontuacaoadv= pontuacaoadv + valortruco + 1;
								else
									pontuacaomao= pontuacaomao + valortruco + 1;
								placaradv.setText( String.valueOf(pontuacaoadv));
								placarmao.setText( String.valueOf(pontuacaomao));
								reiniciaPartida();
							}
						}    
					}
					else if ( msg.what == 3 ) //Recebeu a carta 3
					{
						if ( cartaadv.getVisibility()==View.GONE )
							cartaadv.setVisibility(View.VISIBLE);
						cartaadv.setImageResource(Resource.getResource(truco.baralho.get(6)));   
						ultimajogadaadv=6;
						if ( cartaadv.getVisibility() == View.VISIBLE && cartamao.getVisibility()== View.VISIBLE ){
							if (  truco.cards.indexOf(truco.baralho.get(6)) > truco.cards.indexOf(truco.baralho.get(ultimajogada)) ) {
								parcialpontuacaoadv++;
							}
							else{
								parcialpontuacaomao++;
							}
							cartaadv.setVisibility(View.GONE);
							cartamao.setVisibility(View.GONE);
							qntturno++;
							if ( qntturno == 3){
								valortruco=valortruco>0?valortruco-1:valortruco;
								if ( parcialpontuacaoadv > parcialpontuacaomao) 
									pontuacaoadv= pontuacaoadv + valortruco + 1;
								else
									pontuacaomao= pontuacaomao + valortruco + 1;
								placaradv.setText( String.valueOf(pontuacaoadv));
								placarmao.setText( String.valueOf(pontuacaomao));
								reiniciaPartida();
							}
						}     
					}else if ( msg.what == 4 )
					{
						String msgdiag = "";
						if ( valortruco == 0)
							msgdiag = "Truco";
						else if ( valortruco == 3)
							msgdiag = "6";
						else if ( valortruco == 6)
							msgdiag = "9";
						else if ( valortruco == 9)
							msgdiag = "12";
						Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						 v.vibrate(1000);
						new AlertDialog.Builder(TrucoBTActivity.this)
						.setTitle(msgdiag)
						.setMessage("Aceitar")
						.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) { 
								respostaTrucoS();
								truco.setTurno(truco.getTurno() == 0 ? 1 : 0);			
								valortruco+=3;
								if ( valortruco == 3)
									botaotruco.setText("6");
								else if ( valortruco == 6)
									botaotruco.setText("9");
								else if ( valortruco == 9)
									botaotruco.setText("12");
								if ( valortruco >= 12){
									botaotruco.setVisibility(View.GONE);
								}
							}
						})
						.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) { 
								pontuacaoadv++;
								valortruco=valortruco>0?valortruco-1:valortruco;
								pontuacaoadv+=valortruco;
								placaradv.setText( String.valueOf(pontuacaoadv));
								respostaTrucoN();
							}
						})
						.setIcon(android.R.drawable.ic_dialog_alert)
						.show();
						
					}else if ( msg.what == 5 )   // Aceitou o truco
					{
						if ( valortruco >= 12){
							botaotruco.setVisibility(View.GONE);
						}
						valortruco+=3;	
						if ( valortruco == 3)
							botaotruco.setText("6");
						else if ( valortruco == 6)
							botaotruco.setText("9");
						else if ( valortruco == 9)
							botaotruco.setText("12");
						if ( valortruco >= 12)
							botaotruco.setVisibility(View.GONE);
						truco.setTurno(previewSizePref.getInt("server", 0) == truco.turno?truco.turno:truco.getTurno() == 0 ? 1 : 0);	
					}else if ( msg.what == 6 )    // Negou o truco
					{
						pontuacaomao++;
						valortruco=valortruco>0?valortruco-1:valortruco;
						pontuacaomao+=valortruco;
						placarmao.setText( String.valueOf(pontuacaomao));
						reiniciaPartida();
					}else if ( msg.what == 100 )
					{
						vira.setImageResource(Resource.getResource(truco.baralho.get(0)));   
						carta1.setImageResource(Resource.getResource(truco.baralho.get(1)));
						carta2.setImageResource(Resource.getResource(truco.baralho.get(2)));
						carta3.setImageResource(Resource.getResource(truco.baralho.get(3))); 
					}
				}
			};
		}).start();
	}
	
	
	/**Verifica se a partida chegou ao fim**/
	private void verificaFim() {
		if( pontuacaoadv >= 12 ){
	    	Intent i=new Intent(this,PerdeuActivity.class);
	    	finish();
	    	startActivity(i);
		}
		if (pontuacaomao >= 12){
	    	Intent i=new Intent(this,GanhouActivity.class);
	    	finish();
	    	startActivity(i);
		}
	}
	// Fim Verifica
	
	
	/**Envia respota do Truco**/
	public void respostaTrucoS(){
		sendMessage("5 ");
	}
	public void respostaTrucoN(){
		sendMessage("6 ");
		reiniciaPartida();
	}
	// Fim Envia
	
	
	/** Manipula o baralho recebido **/
	private void handleReceivedMessage(String[] msgArray) {
		Log.i("Pai", "recebendo");
		if (msgArray[0].contains("100")) {
			truco.baralho.set(0, msgArray[1].toString());
			truco.baralho.set(1, msgArray[5].toString());
			truco.baralho.set(2, msgArray[6].toString());
			truco.baralho.set(3, msgArray[7].toString());
			truco.baralho.set(4, msgArray[2].toString());
			truco.baralho.set(5, msgArray[3].toString());
			truco.baralho.set(6, msgArray[4].toString());
			truco.turno = 0;
		}
	}
	//Fim manipulação

}